/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import type { SizeType } from 'antd/lib/config-provider/SizeContext';
import { isArray } from 'lodash';
import { CSSProperties } from 'react';

export type CityCascaderType = 'all' | 'province' | 'city';
export interface CityCascaderProps {
  size?: SizeType;
  onChange?: (v: string[]) => void;
  placeholder?: string;
  type?: CityCascaderType;
  value?: string[];
  allowClear?: boolean;
  style?: CSSProperties;
  disabled?: boolean;
  fullName?: boolean;
}

export interface AreaDataItem {
  value: string;
  label: string;
  children?: AreaDataItem[];
}
export interface AreaDataListItem extends AreaDataItem {
  children?: AreaDataItem[];
}

export interface AreaItem {
  id: string;
  pid: number;
  name: string;
}

/**
 *
 * @description 根据type生成placeholder
 * @param type
 * @returns
 */
export function createDefaultPlaceholder(type: CityCascaderType = 'all'): string {
  const p = ['省', '市', '区'];
  const t = ['province', 'city', 'all'];
  return `选择${p.slice(0, t.findIndex((item) => item === type) + 1).join('')}`;
}

let formattedAddressList: AreaDataListItem[] | null = null;

/**
 *
 * @description 格式化区域列表
 * @param area
 * @param type
 * @returns
 */
export function formatAreaList(area: AreaItem[][], type?: CityCascaderType): AreaDataListItem[] {
  if (formattedAddressList) {
    return formattedAddressList;
  }
  if (!isArray(area)) return [];

  const list: AreaDataListItem[] = [];
  const areaLen = area.length;
  const pIdIndex = {};
  const cIdIndex = {};
  const isProvince = type === 'province';
  const isCity = type === 'city';
  for (let p = 0; p < areaLen; p++) {
    const arr = (area[p] || []).filter((item: any) => !!item);
    const arrLen = arr.length;
    if (arrLen > 0) {
      for (let i = 0; i < arrLen; i++) {
        const { id, pid, name } = arr[i] || {};
        if (!name) continue;
        const data: AreaDataItem = {
          value: name,
          label: name,
        };
        if (p === 1 && 1 * pid === 0) {
          list.push(data);
          pIdIndex[id] = list.length - 1;
        } else if (p === 2) {
          // 市
          if (isProvince) {
            continue;
          }
          const parent: any = list[pIdIndex[pid]];
          parent.children = parent.children || [];
          parent.children.push(data);
          cIdIndex[id] = parent.children.length - 1;
        } else {
          // 区
          if (isProvince || isCity) {
            continue;
          }
          const currentCity = area[2][pid];
          if (!currentCity) continue;
          const cIndex = cIdIndex[pid];
          const pIndex = pIdIndex[currentCity.pid];
          const parent = list[pIndex].children![cIndex];
          parent.children = parent.children || [];
          parent.children.push(data);
        }
      }
    }
  }
  formattedAddressList = list;
  return list;
}
